package com.tfswx.jcyw.dmzc.linstener;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManagerListener;
import com.tfswx.jcyw.dmzc.service.DlxxService;
import com.tfswx.jcyw.dmzc.util.NotificationUtil;
import com.tfswx.jcyw.dmzc.window.DmzcSettingWindow;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public final class MyProjectListener implements ProjectManagerListener {

    private static final List<Project> PROJECT_LIST = new CopyOnWriteArrayList<>();

    public static Project getProject(String gcmc) {
        for (Project project : PROJECT_LIST) {
            if (project.getName().equals(gcmc)) {
                return project;
            }
        }
        return null;
    }

    @Override
    public void projectOpened(final @NotNull Project project) {
        PROJECT_LIST.add(project);

        DlxxService dlxxState = DlxxService.getInstance();
        String rybm = dlxxState.getRybm();
        if (StringUtils.isBlank(rybm)) {
            Notification notification = NotificationUtil.create("未登录", "代码走查", NotificationType.WARNING);
            notification.addAction(new AnAction("登录") {
                @Override
                public void actionPerformed(@NotNull AnActionEvent e) {
                    DmzcSettingWindow.openSetting(project);
                }
            });
            notification.notify(project);
        }

    }

    @Override
    public void projectClosed(@NotNull Project project) {
        PROJECT_LIST.remove(project);
    }
}
